package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordType;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.business.BusinessDO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessListDTO;
import com.qk.dto.business.BusinessPoolDTO;
import com.qk.dto.business.UpdateBusinessInfoDTO;
import com.qk.entity.*;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.vo.business.BusinessVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author diva
 * @date 2025/10/15 10:53
 * @ProjectName
 */

@Slf4j
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;
    @Override
    public PageResult<BusinessDO> businessList(BusinessListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<BusinessDO> list = this.baseMapper.selectByPage(dto);
        Page<BusinessDO> page = (Page<BusinessDO>) list;
        return PageResult.<BusinessDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void addBusiness(BusinessDTO dto) {
        Business business = BeanUtil.copyProperties(dto,Business.class);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        this.baseMapper.insert(business);
    }

    @Override
    public BusinessVO getBusinessById(Integer id) {
        Business business = this.baseMapper.selectById(id);
        Integer userId = business.getUserId();
        User user = userMapper.selectById(userId);
        List<BusinessTrackRecord> businessTrackRecords =
                        businessTrackRecordMapper.selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class)
                        .in(BusinessTrackRecord::getBusinessId,id));
        BusinessVO businessvo = BeanUtil.copyProperties(business,BusinessVO.class);
        List<BusinessVO.BusinessTrackRecordVO> list = businessTrackRecords.stream().map(item -> {
            BusinessVO.BusinessTrackRecordVO vo = BeanUtil.copyProperties(item,BusinessVO.BusinessTrackRecordVO.class);
            BeanUtil.copyProperties(item,vo);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        businessvo.setTrackRecords(list);
        return businessvo;
    }

    @Override
    public PageResult<Business> businessPool(BusinessPoolDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Business> list = this.baseMapper.selectPool(dto);
        Page<Business> page = (Page<Business>) list;
        return PageResult.<Business>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }
    @Transactional
    @Override
    public void updateBusinessInfoById(UpdateBusinessInfoDTO dto) {
        log.info("==============BusinessServiceImpl中的updateBusinessInfoById处理线程名称是={}",Thread.currentThread().getName());
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setUpdateTime(LocalDateTime.now());
        if(dto.getStatus() == BusinessStatusConstants.WAIT_FOLLOW_UP){
            business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        }
        this.baseMapper.updateById(business);

        // 创建商机跟进记录
        BusinessTrackRecord businessTrackRecord = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        businessTrackRecord.setCreateTime(LocalDateTime.now());
        businessTrackRecord.setId(null);
        businessTrackRecord.setBusinessId(business.getId());
        // 使用ClueTrackRecordType.NORMAL表示普通跟进记录
        businessTrackRecord.setUserId(CurrentUserContextHolders.get());
        this.businessTrackRecordMapper.insert(businessTrackRecord);
    }

    @Override
    public void toCustomer(Integer businessId) {
        Business business = this.baseMapper.selectById(businessId);
        business.setStatus(BusinessStatusConstants.CONVERT_TO_CUSTOMER);
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);

        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        customer.setUpdateTime(LocalDateTime.now());
        customer.setCreateTime(LocalDateTime.now());
        customer.setBusinessId(businessId);
        this.customerMapper.insert(customer);
    }


}
